<template>
  <PageContainer title="质检统计">
    <!-- 时间筛选区域 -->
    <el-card class="filter-card" style="margin-bottom: 20px;">
      <el-form inline>
        <el-form-item label="统计时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="统计维度">
          <el-select v-model="dimension" @change="handleDimensionChange">
            <el-option label="按日统计" value="day" />
            <el-option label="按周统计" value="week" />
            <el-option label="按月统计" value="month" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <StatCard
        :icon="Document"
        icon-bg="#409EFF"
        :value="overallStats.totalExceptions"
        label="异常总数"
        :trend="overallStats.exceptionTrend"
      />
      <StatCard
        :icon="Check"
        icon-bg="#67C23A"
        :value="overallStats.handledCount"
        label="已处理"
        :trend="overallStats.handledTrend"
      />
      <StatCard
        :icon="Money"
        icon-bg="#F56C6C"
        :value="`¥${overallStats.totalDeduction}`"
        label="总扣款"
        :trend="overallStats.deductionTrend"
      />
      <StatCard
        :icon="Coin"
        icon-bg="#67C23A"
        :value="`¥${overallStats.totalAddition}`"
        label="总补款"
        :trend="overallStats.additionTrend"
      />
      <StatCard
        :icon="Timer"
        icon-bg="#E6A23C"
        :value="`${overallStats.avgHandleTime}分钟`"
        label="平均处理时间"
        :trend="overallStats.timeTrend"
      />
      <StatCard
        :icon="SuccessFilled"
        icon-bg="#67C23A"
        :value="`${overallStats.accuracyRate}%`"
        label="处理准确率"
        :trend="overallStats.accuracyTrend"
      />
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <!-- 异常趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>异常处理趋势</span>
            <el-button-group>
              <el-button
                :type="trendType === 'exception' ? 'primary' : 'default'"
                size="small"
                @click="trendType = 'exception'"
              >
                异常数量
              </el-button>
              <el-button
                :type="trendType === 'handle' ? 'primary' : 'default'"
                size="small"
                @click="trendType = 'handle'"
              >
                处理数量
              </el-button>
            </el-button-group>
          </div>
        </template>
        <div ref="trendChartRef" class="chart-container"></div>
      </el-card>

      <!-- 异常类型分布 -->
      <el-card class="chart-card">
        <template #header>
          <span>异常类型分布</span>
        </template>
        <div ref="typeChartRef" class="chart-container"></div>
      </el-card>

      <!-- 处理结果分布 -->
      <el-card class="chart-card">
        <template #header>
          <span>处理结果分布</span>
        </template>
        <div ref="resultChartRef" class="chart-container"></div>
      </el-card>

      <!-- 质检员工作量 -->
      <el-card class="chart-card">
        <template #header>
          <span>质检员工作量</span>
        </template>
        <div ref="workloadChartRef" class="chart-container"></div>
      </el-card>
    </div>

    <!-- 详细统计表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>详细统计数据</span>
          <div class="header-actions">
            <el-button
              type="success"
              size="small"
              @click="handleExport"
            >
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 按时间统计 -->
        <el-tab-pane label="时间统计" name="time">
          <DataTable
            :data="timeStatsList"
            :loading="loading"
            :show-pagination="false"
          >
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="exceptionCount" label="异常数量" width="100" />
            <el-table-column prop="handledCount" label="已处理" width="100" />
            <el-table-column prop="pendingCount" label="待处理" width="100" />
            <el-table-column prop="deductionAmount" label="扣款金额" width="120">
              <template #default="{ row }">
                <span class="amount-text negative">¥{{ row.deductionAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="additionAmount" label="补款金额" width="120">
              <template #default="{ row }">
                <span class="amount-text positive">¥{{ row.additionAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="avgHandleTime" label="平均处理时间" width="120">
              <template #default="{ row }">
                {{ row.avgHandleTime }}分钟
              </template>
            </el-table-column>
            <el-table-column prop="accuracyRate" label="准确率" width="100">
              <template #default="{ row }">
                <span class="accuracy-rate">{{ row.accuracyRate }}%</span>
              </template>
            </el-table-column>
          </DataTable>
        </el-tab-pane>

        <!-- 按异常类型统计 -->
        <el-tab-pane label="异常类型" name="type">
          <DataTable
            :data="typeStatsList"
            :loading="loading"
            :show-pagination="false"
          >
            <el-table-column prop="exceptionType" label="异常类型" width="150">
              <template #default="{ row }">
                {{ getExceptionTypeText(row.exceptionType) }}
              </template>
            </el-table-column>
            <el-table-column prop="count" label="数量" width="100" />
            <el-table-column prop="percentage" label="占比" width="100">
              <template #default="{ row }">
                {{ row.percentage }}%
              </template>
            </el-table-column>
            <el-table-column prop="handledCount" label="已处理" width="100" />
            <el-table-column prop="avgHandleTime" label="平均处理时间" width="120">
              <template #default="{ row }">
                {{ row.avgHandleTime }}分钟
              </template>
            </el-table-column>
            <el-table-column prop="deductionRate" label="扣款率" width="100">
              <template #default="{ row }">
                {{ row.deductionRate }}%
              </template>
            </el-table-column>
            <el-table-column prop="additionRate" label="补款率" width="100">
              <template #default="{ row }">
                {{ row.additionRate }}%
              </template>
            </el-table-column>
          </DataTable>
        </el-tab-pane>

        <!-- 按质检员统计 -->
        <el-tab-pane label="质检员统计" name="inspector">
          <DataTable
            :data="inspectorStatsList"
            :loading="loading"
            :show-pagination="false"
          >
            <el-table-column prop="inspectorName" label="质检员" width="120" />
            <el-table-column prop="handledCount" label="处理数量" width="100" />
            <el-table-column prop="avgHandleTime" label="平均处理时间" width="120">
              <template #default="{ row }">
                {{ row.avgHandleTime }}分钟
              </template>
            </el-table-column>
            <el-table-column prop="accuracyRate" label="准确率" width="100">
              <template #default="{ row }">
                <span class="accuracy-rate">{{ row.accuracyRate }}%</span>
              </template>
            </el-table-column>
            <el-table-column prop="deductionCount" label="扣款次数" width="100" />
            <el-table-column prop="additionCount" label="补款次数" width="100" />
            <el-table-column prop="noAdjustmentCount" label="无需调整" width="100" />
            <el-table-column prop="workEfficiency" label="工作效率" width="100">
              <template #default="{ row }">
                <el-tag :type="getEfficiencyTag(row.workEfficiency)">
                  {{ getEfficiencyText(row.workEfficiency) }}
                </el-tag>
              </template>
            </el-table-column>
          </DataTable>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  Document,
  Check,
  Money,
  Coin,
  Timer,
  SuccessFilled,
  Refresh,
  Download
} from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import DataTable from '@/components/DataTable.vue'
import StatCard from '@/components/StatCard.vue'
import { useQualityStore } from '@/stores/quality'

const qualityStore = useQualityStore()

const loading = ref(false)
const dateRange = ref<string[]>([])
const dimension = ref('day')
const trendType = ref('exception')
const activeTab = ref('time')

// 图表引用
const trendChartRef = ref<HTMLElement>()
const typeChartRef = ref<HTMLElement>()
const resultChartRef = ref<HTMLElement>()
const workloadChartRef = ref<HTMLElement>()

// 图表实例
let trendChart: echarts.ECharts | null = null
let typeChart: echarts.ECharts | null = null
let resultChart: echarts.ECharts | null = null
let workloadChart: echarts.ECharts | null = null

// 总体统计
const overallStats = reactive({
  totalExceptions: 1256,
  exceptionTrend: '+12.5%',
  handledCount: 1189,
  handledTrend: '+8.3%',
  totalDeduction: '12,580.50',
  deductionTrend: '-5.2%',
  totalAddition: '8,750.30',
  additionTrend: '+15.8%',
  avgHandleTime: 8.5,
  timeTrend: '-2.1%',
  accuracyRate: 96.8,
  accuracyTrend: '+1.2%'
})

// 时间统计列表
const timeStatsList = ref([
  {
    date: '2024-01-15',
    exceptionCount: 45,
    handledCount: 42,
    pendingCount: 3,
    deductionAmount: '580.50',
    additionAmount: '320.00',
    avgHandleTime: 8.2,
    accuracyRate: 97.5
  },
  {
    date: '2024-01-14',
    exceptionCount: 38,
    handledCount: 38,
    pendingCount: 0,
    deductionAmount: '420.30',
    additionAmount: '180.00',
    avgHandleTime: 7.8,
    accuracyRate: 96.8
  }
])

// 异常类型统计列表
const typeStatsList = ref([
  {
    exceptionType: 'weight_error',
    count: 456,
    percentage: 36.3,
    handledCount: 432,
    avgHandleTime: 9.2,
    deductionRate: 65.2,
    additionRate: 28.5
  },
  {
    exceptionType: 'classification_error',
    count: 523,
    percentage: 41.6,
    handledCount: 498,
    avgHandleTime: 7.8,
    deductionRate: 45.8,
    additionRate: 35.2
  },
  {
    exceptionType: 'image_mismatch',
    count: 277,
    percentage: 22.1,
    handledCount: 259,
    avgHandleTime: 8.5,
    deductionRate: 52.1,
    additionRate: 31.2
  }
])

// 质检员统计列表
const inspectorStatsList = ref([
  {
    inspectorName: '张质检',
    handledCount: 342,
    avgHandleTime: 7.8,
    accuracyRate: 97.2,
    deductionCount: 156,
    additionCount: 98,
    noAdjustmentCount: 88,
    workEfficiency: 'high'
  },
  {
    inspectorName: '李质检',
    handledCount: 398,
    avgHandleTime: 8.2,
    accuracyRate: 96.5,
    deductionCount: 189,
    additionCount: 112,
    noAdjustmentCount: 97,
    workEfficiency: 'high'
  },
  {
    inspectorName: '王质检',
    handledCount: 289,
    avgHandleTime: 7.5,
    accuracyRate: 98.1,
    deductionCount: 132,
    additionCount: 85,
    noAdjustmentCount: 72,
    workEfficiency: 'medium'
  }
])

// 获取异常类型文本
const getExceptionTypeText = (type: string) => {
  switch (type) {
    case 'weight_error':
      return '重量异常'
    case 'classification_error':
      return '分类错误'
    case 'image_mismatch':
      return '图像不符'
    default:
      return '其他'
  }
}

// 获取效率标签
const getEfficiencyTag = (efficiency: string) => {
  switch (efficiency) {
    case 'high':
      return 'success'
    case 'medium':
      return 'warning'
    case 'low':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取效率文本
const getEfficiencyText = (efficiency: string) => {
  switch (efficiency) {
    case 'high':
      return '高效'
    case 'medium':
      return '中等'
    case 'low':
      return '较低'
    default:
      return '未知'
  }
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['异常数量', '处理数量']
    },
    xAxis: {
      type: 'category',
      data: ['01-10', '01-11', '01-12', '01-13', '01-14', '01-15', '01-16']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '异常数量',
        type: 'line',
        data: [32, 28, 45, 38, 42, 45, 35],
        smooth: true,
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '处理数量',
        type: 'line',
        data: [30, 28, 42, 38, 38, 42, 33],
        smooth: true,
        itemStyle: { color: '#67C23A' }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化异常类型图表
const initTypeChart = () => {
  if (!typeChartRef.value) return
  
  typeChart = echarts.init(typeChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '异常类型',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 523, name: '分类错误' },
          { value: 456, name: '重量异常' },
          { value: 277, name: '图像不符' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  typeChart.setOption(option)
}

// 初始化处理结果图表
const initResultChart = () => {
  if (!resultChartRef.value) return
  
  resultChart = echarts.init(resultChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '处理结果',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '30',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 477, name: '扣款', itemStyle: { color: '#F56C6C' } },
          { value: 295, name: '补款', itemStyle: { color: '#67C23A' } },
          { value: 417, name: '无需调整', itemStyle: { color: '#909399' } }
        ]
      }
    ]
  }
  
  resultChart.setOption(option)
}

// 初始化工作量图表
const initWorkloadChart = () => {
  if (!workloadChartRef.value) return
  
  workloadChart = echarts.init(workloadChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['张质检', '李质检', '王质检']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '处理数量',
        type: 'bar',
        data: [342, 398, 289],
        itemStyle: { color: '#409EFF' }
      }
    ]
  }
  
  workloadChart.setOption(option)
}

// 初始化所有图表
const initCharts = () => {
  nextTick(() => {
    initTrendChart()
    initTypeChart()
    initResultChart()
    initWorkloadChart()
  })
}

// 处理日期变化
const handleDateChange = () => {
  refreshData()
}

// 处理维度变化
const handleDimensionChange = () => {
  refreshData()
}

// 处理标签页变化
const handleTabChange = () => {
  // 可以根据不同标签页加载不同数据
}

// 刷新数据
const refreshData = () => {
  loading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    ElMessage.success('数据已刷新')
    loading.value = false
  }, 1000)
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 监听趋势类型变化
watch(trendType, () => {
  // 重新渲染趋势图表
  if (trendChart) {
    // 根据趋势类型更新图表数据
    initTrendChart()
  }
})

// 窗口大小变化时重新调整图表
const handleResize = () => {
  trendChart?.resize()
  typeChart?.resize()
  resultChart?.resize()
  workloadChart?.resize()
}

onMounted(() => {
  // 设置默认日期范围（最近7天）
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 7)
  
  dateRange.value = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]
  
  initCharts()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.filter-card {
  .el-form {
    margin-bottom: 0;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .chart-container {
    height: 300px;
    width: 100%;
  }
}

.table-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
}

.amount-text {
  font-weight: 600;

  &.positive {
    color: #67c23a;
  }

  &.negative {
    color: #f56c6c;
  }
}

.accuracy-rate {
  font-weight: 600;
  color: #67c23a;
}

@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .chart-container {
    height: 250px;
  }
}
</style>